package com.naizhuai.util;

import com.naizhuai.network.HttpResultFunc;
import com.naizhuai.network.entity.ResultResponse;
import com.naizhuai.network.exception.ServerException;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * rxjava自定义转换器
 * Created by code_han on 2018/2/23.
 */

public class RxUtils {

    private static final Observable.Transformer schedulersTransformer = observable -> ((Observable) observable)
            .subscribeOn(Schedulers.io())
            .retryWhen(new RetryWithDelay(3, 2000))
            .map(new Func1<ResultResponse<Object>, Object>() {
                @Override
                public Object call(ResultResponse<Object> listResultResponse){
                    NaizhuAILog.e("listResultResponse.isRet()" + listResultResponse.isRet());
                    if (!listResultResponse.isRet()) {
                        throw new ServerException(listResultResponse.getRes().getResult().getCode(), listResultResponse.getRes().getResult().getResultMsg());
                    } else {
                        if (listResultResponse.getRes().getSource() == null)
                            return listResultResponse.getRes().getResultCode();
                        return listResultResponse.getRes().getSource();
                    }
                }
            })
            .observeOn(AndroidSchedulers.mainThread())
            .onErrorResumeNext(new HttpResultFunc<>());

    public static <T> Observable.Transformer<ResultResponse<T>, T> applySchedulers() {
        return (Observable.Transformer<ResultResponse<T>, T>) schedulersTransformer;
    }

    public static boolean isNetRunning(Subscription sub){
        return !(sub == null || sub.isUnsubscribed());
    }


}
